<template>
  <div class="search">
    <Row>
      <Col>
        <Card>
          <Row>
            <Col :span="5">
              <Button @click="getList" icon="md-refresh" style="margin-right:10px">刷新</Button>
            </Col>
            <Col :span="19">
              <Form ref="searchForm" inline :model="searchForm" :label-width="85">
                <FormItem label="套餐分类" prop="goodCategoryId">
                  <Poptip trigger="click" placement="right-start" title="分类" width="100%">
                      <Input v-model="searchForm.goodCategoryName" style="width:100%" readonly placeholder="请选择商品分类" />
                      <div slot="content" style="position:relative;min-height:5vh">
                        <Tree :data="classifyData" :load-data="loadData" @on-select-change="selectOneTreeEdit" ref="treeOne"></Tree>
                        <Spin size="large" fix v-if="loadingEdit"></Spin>
                      </div>
                  </Poptip> 
                </FormItem>
                <FormItem label="套餐名称">
                  <Input v-model="searchForm.goodName" clearable placeholder="套餐名称" class="itemInput" />
                </FormItem>
                <Form-item style="margin-left:-40px">
                  <Button type="default" @click="clearIpt" style="margin-right:10px">清空</Button>
                  <Button type="primary" @click="handleSearch" style="margin-right:10px">搜索</Button>
                </Form-item>
              </Form>
            </Col>
          </Row>

          <Row>
            <Table :loading="loading" border :columns="commodityColumns" :data="commodityData" ref="table" sortable="custom" @on-sort-change="changeSort"></Table>
          </Row>

          <Row type="flex" justify="end" class="page">
            <Page :current="searchForm.pageNumber" :total="pageTotal" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
          </Row>
        </Card>
      </Col>
    </Row>
    
    <!-- 查看大图 -->
    <Modal title="查看大图" v-model="visible" class="imgModal">
      <img :src="imgSrc" style="width: 100%" />
    </Modal>

  </div>
</template>

<script>
import {
  getCategoryList,
  removeCommodity,
  addCommodity,
  editCommodity
} from "@/api/commodity";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import editor from "@/views/my-components/xboot/editor";
export default {
  components: {
    uploadPicInput,
    editor
  },
  data() {
    return {
      index: 1,
      loading: true,
      visible: false,
      modal1:false,
      lookPreVisible: false,
      imgSrc: "",
      pageTotal: 0, //总条数
      modalTitle: "添加商品",
      commodityData: [],
      category: [],
      //商品显示
      commodityColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "套餐名称",
          key: "goodName"
        },
        {
          title: "商家名称",
          key: "shopName"
        },  
        {
          title: "套餐图片",
          slot: "action",
          key: "goodPics",
          render: (h,params) => {
            var imgs = params.row.goodPics.split(",");
            return h("img", {
              attrs: {
                src: imgs[0]
              },
              style: {
                width: "40px",
                height: "30px"
              },
              on: {
                click: ()=> {
                  this.handleView(imgs[0])
                }
              }
            })
          }
        },      
        {
          title: "套餐原价",
          key: "goodOldPrice"
        },
        {
          title: "套餐现价",
          key: "goodNewPrice"
        },
        {
          title: "分类名称",
          key: "goodCategoryName"
        },
        {
          title: "创建时间",
          key: "createTime"
        },
        // {
        //   title: "积分",
        //   key: "integral"
        // },        
        {
          title: "操作",
          slot: "caozuo",
          width: 160,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px",
                    display:(params.row.delFlag==1)?"none":"inline-block"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "下架"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "default",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px",
                    display:(params.row.delFlag==0)?"none":"inline-block"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "上架"
              ),
            ]);
          }
        }
      ],
      searchForm: {
        pageNumber: 1,
        pageSize: 10,
        goodName: "",
        goodCategoryId: "",
        goodCategoryName: ""
      },
      addForm: {
        goodCategoryId: "",
        goodCategoryName: "",
        goodName: "",
        goodPics: "",
        goodOldPrice: "",
        goodNewPrice: "",
        typeEnum: "GOODSPACKAGE",
        // integral: 0
      },
      formRules: {
        goodName: [{ required: true, message: "请输入商品名称", trigger: "blur" },
          { type: 'string', max: 30, message: '商品名称不能多于30字', trigger: 'blur' }],
        goodCategoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
        goodPics: [{ required: true, message: "请选择商品轮播", trigger: "blur" }],
        goodNewPrice: [{ required: true, message: "请输入商品原价", trigger: "blur",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ },
                    { required: true, message: "商品原价格式不正确",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/}],
        goodOldPrice: [{ required: true, message: "请输入商品现价", trigger: "blur",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ },
                    { required: true, message: "商品现价格式不正确",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/}],
        // integral: [ { required: true, message: "商品积分只能为正整数", trigger: "blur", pattern: /(^[1-9]\d*$)/ }],
      },
      submitLoading: false,
      goodId: "",
      goodsPackageId:"",
      modalStatus: 0,
      classifyData: [],
      loadingEdit: false,
    };
  },
  methods: {
    selectTwoTreeEdit(v){
      console.log(v);
      if (v[0].parentId === "0") {
        this.$Message.warning("添加或修改商品只能选择子节点")
      } else {
        var data = {
          pid:v[0].id
        }
        this.addForm.goodCategoryId = v[0].id;
        this.addForm.goodCategoryName = v[0].title;
        this.$forceUpdate();
      }
    },

    selectOneTreeEdit(v){
      console.log(v);
      var data = {
        pid:v[0].id
      }
      this.searchForm.goodCategoryId = v[0].id;
      this.searchForm.goodCategoryName = v[0].title;
      this.$forceUpdate();
    },

    clearIpt () {
      this.searchForm.goodCategoryId = "";
      this.searchForm.goodCategoryName = "";
      let data = this.$refs.treeOne.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.searchForm.shopName = "";
      this.searchForm.goodName = "";
    },

    changeSort () {

    },

    removeSpecification (v) {
      console.log(v)
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的规格数据?",
        loading: true,
        onOk: () => {
          var param = {
            ids: v.id
          }
          // 批量删除
          this.postRequest("/goodsIntroduce/removeGoodsIntroduce",param).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.$Modal.remove()
            }
          });
        }
      });
    },

    // 获取分类列表
    getCategory() {
      getCategoryList().then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            e.title=e.title;
              if (e.isParent) {
                e.loading = false;
                e.children = [];
              }
            });
          this.classifyData = res.result;
        }
      });
    },
    
    // 获取商品列表
    getList() {
        // 分类id是个数组，这里转为字符串
      let data = {}
      let searchForm = this.searchForm
      for(let key in searchForm) {
          if (Array.isArray(searchForm[key])) {
          // data[key].slice(key.length - 1) 数组的最后一个元素
          let length = searchForm[key].length;
          data[key] = searchForm[key][length - 1];
         } else {
          data[key] = searchForm[key];
         }
      }
      this.postRequest("/good/PCgoodsPackageList", data).then(res=> {
        this.loading = false
        if (res.success) {
          this.commodityData = res.result.data;
          this.pageTotal = res.result.size
          console.log(res);
        }
      })
    },

    // 搜索商品
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.getList()
    },

    loadData(item, callback) { 
        // 异步加载树子节点数据
      var param ={
        pid:item.id
      }
      this.postRequest("/goodCategory/getGoodCategoryList",param).then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            e.title=e.title
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        }
      });
    },

    // 删除商品
    remove(v) {
        removeCommodity({
            id: v.id
          }).then(res => {
            if(res.success) {
              this.$Message.success('操作成功')
              this.getList();
            }else{
              this.$Message.error('操作失败');
            }
          })
    },
    // 切换页
    changePage(num) {
        this.searchForm.pageNumber = num
        this.getList()
    },
    // 切换每页显示条数
    changePageSize (num) {
        this.searchForm.pageSize = num;
        this.getList()
    },
    // 放大图片
    handleView(src) {
      this.visible = true;
      this.imgSrc = src;
    },
  
  },
  created() {
    this.getCategory();
    this.getList();
  }
};
</script>

<style>
.commodity-content {
  padding: 16px;
  background-color: #ffffff;
}
.itemInput {
  width: 160px;
}
.selected {
  width: 50%;
}
.imgModal {
  text-align: center;
}
.img {
  width: 50px;
  height: 50px;
}
.page{
        margin: 16px;
        overflow: hidden;
        text-align: right;
    }
.paygos{
  margin-top: 40px;
}
.paygo1{
  margin-top: -50px;
}
</style>